import 'package:flutter/material.dart';
import 'package:flutter_deer/database/beans/discount/discount_page_item_entity.dart';
import 'package:flutter_deer/res/colors.dart';
import 'package:flutter_deer/ui/cashier/item/coupon_item.dart';
import 'package:flutter_deer/ui/cashier/provider/cashier_page_provider.dart';
import 'package:flutter_deer/util/toast_utils.dart';
import 'package:flutter_deer/widgets/press_blue_button.dart';
import 'package:get/get.dart';

class CouponSelectDialog extends StatefulWidget {
  const CouponSelectDialog({super.key});

  @override
  State<CouponSelectDialog> createState() => _CouponSelectDialogState();
}

class _CouponSelectDialogState extends State<CouponSelectDialog> with SingleTickerProviderStateMixin {
  late TabController _tabController;
  final ScrollController _scrollController1 = ScrollController();
  final ScrollController _scrollController2 = ScrollController();
  final GlobalKey<RefreshIndicatorState> _refreshKey1 = GlobalKey<RefreshIndicatorState>();
  final GlobalKey<RefreshIndicatorState> _refreshKey2 = GlobalKey<RefreshIndicatorState>();
  List<CouponBean> _usableItems = [];
  List<CouponBean> _unusableItems = [];
  bool _isLoading1 = false;
  bool _isLoading2 = false;
  int _page1 = 1;
  int _page2 = 1;
  final mProvider = Get.find<CashierPageProvider>();

  List<CouponBean> _defaultItems = [];

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    // 使用 addPostFrameCallback 延迟加载数据
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _loadInitialData();
    });
    _setupScrollListeners();
  }

  @override
  void dispose() {
    _tabController.dispose();
    _scrollController1.dispose();
    _scrollController2.dispose();
    super.dispose();
  }

  void _loadInitialData() {
    // 模拟加载初始数据
    mProvider.getMemberCouponList(success: (list) {
      final mSelect = list?.where((x) => x.selected == true).toList() ?? [];
      mProvider.selectedCoupon.value = mSelect;
      _defaultItems = mSelect;
      if (list != null) {
        setState(() {
          _usableItems = list;
        });
      }
    });

    // _unusableItems = List.generate(
    //     20,
    //     (index) => CouponBean(
    //           id: index + 100,
    //           title: '不可用项目 $index',
    //           isUsable: false,
    //         ));
  }

  void _setupScrollListeners() {
    _scrollController1.addListener(() {
      if (_scrollController1.position.pixels == _scrollController1.position.maxScrollExtent && !_isLoading1) {
        _loadMoreData(1);
      }
    });

    _scrollController2.addListener(() {
      if (_scrollController2.position.pixels == _scrollController2.position.maxScrollExtent && !_isLoading2) {
        _loadMoreData(2);
      }
    });
  }

  Future<void> _loadMoreData(int tabIndex) async {
    if (tabIndex == 1) {
      setState(() => _isLoading1 = true);
      await Future.delayed(const Duration(seconds: 1));
      final newItems = List.generate(
          10,
          (index) => CouponBean());
      setState(() {
        _usableItems.addAll(newItems);
        _page1++;
        _isLoading1 = false;
      });
    } else {
      setState(() => _isLoading2 = true);
      await Future.delayed(const Duration(seconds: 1));
      final newItems = List.generate(
          10,
          (index) => CouponBean());
      setState(() {
        _unusableItems.addAll(newItems);
        _page2++;
        _isLoading2 = false;
      });
    }
  }

  // Future<void> _refreshData(int tabIndex) async {
  //   await Future.delayed(const Duration(seconds: 1));
  //   if (tabIndex == 1) {
  //     setState(() {
  //       _usableItems = List.generate(
  //           20,
  //           (index) => CouponBean(
  //                 id: index,
  //                 title: '待使用项目 $index (刷新后)',
  //                  isUsable: true,
  //               ));
  //       _page1 = 1;
  //     });
  //   } else {
  //     setState(() {
  //       _unusableItems = List.generate(
  //           20,
  //           (index) => CouponBean(
  //                 id: index + 100,
  //                 title: '不可用项目 $index (刷新后)',
  //                 isUsable: false,
  //               ));
  //       _page2 = 1;
  //     });
  //   }
  // }

  @override
  Widget build(BuildContext context) {
    final screenSize = MediaQuery.of(context).size;

    return Dialog(
      shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(6)),
      insetPadding: EdgeInsets.zero,
      child: Container(
        width: screenSize.width * 0.8,
        height: screenSize.height * 0.8,
        decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(16),
          color: Colours.bg_color,
        ),
        child: Column(
          children: [
            const SizedBox(height: 10),

            Row(
              children: [
                const SizedBox(width: 16),

                // 左侧选项卡区域
                Container(
                  width: 280,
                  padding: EdgeInsets.zero,
                  decoration: BoxDecoration(
                    color: Colors.white, // 背景色
                    borderRadius: BorderRadius.circular(5), // 圆角
                  ),
                  child: TabBar(
                    padding: const EdgeInsets.symmetric(vertical: 1, horizontal: 0),
                    controller: _tabController,
                    indicator: const BoxDecoration(
                      color: Colors.blue,
                      borderRadius: BorderRadius.all(Radius.circular(5)),
                    ),
                    labelColor: Colors.white,
                    unselectedLabelColor: Colors.black,
                    unselectedLabelStyle: const TextStyle(fontSize: 16),
                    labelStyle: const TextStyle(fontSize: 16),
                    tabs: [
                      Tab(text: '待使用（${mProvider.couponLimit.value.getAvailableCountStr()}）'),
                      Tab(text: '不可用（${mProvider.couponLimit.value.unavailableCount}）'),
                    ],
                    isScrollable: false,
                    indicatorSize: TabBarIndicatorSize.tab,
                    indicatorWeight: 1,
                    physics: const NeverScrollableScrollPhysics(),
                    indicatorPadding: const EdgeInsets.symmetric(vertical: 5, horizontal: 5),
                    // dragStartBehavior: DragStartBehavior.down,
                  ),
                ),

                const Spacer(),

                TextButton(
                  onPressed: () => Navigator.of(context).pop(),
                  child: const Text('取消', style: TextStyle(fontSize: 16)),
                ),

                const SizedBox(width: 10),

                PressBlueButton(
                  text: ' 不使用优惠券 ',
                  onPressed: () => {
                    mProvider.refreshDiscount(clearSelect: true, successCallback: (list) {
                      Navigator.of(context).pop();
                    }),
                  },
                ),

                const SizedBox(width: 10),

                PressBlueButton(
                  text: '确认使用优惠',
                  onPressed: () {
                    if (mProvider.selectedCoupon.isEmpty) {
                      Toast.show('请选择优惠券');
                    } else {
                      mProvider.getCurrentDiscount?.couponSelectType = 1;
                      mProvider.refreshDiscount(successCallback: (list) {
                        Navigator.of(context).pop();
                      });
                    }
                  },
                ),

                const SizedBox(width: 20),
              ],
            ),

            // 右侧内容区域
            Expanded(
              child: TabBarView(
                controller: _tabController,
                physics: const NeverScrollableScrollPhysics(),
                children: [
                  // 待使用内容
                  RefreshIndicator(
                    key: _refreshKey1,
                    onRefresh: () => Future.value(),
                    child: GridView.builder(
                      controller: _scrollController1,
                      padding: const EdgeInsets.all(16),
                      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 400,
                        childAspectRatio: 256 / 175,
                        crossAxisSpacing: 0,
                        mainAxisSpacing: 0,
                      ),
                      itemCount: _usableItems.length + (_isLoading1 ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index < _usableItems.length) {
                          return CouponCard(
                            data: _usableItems[index],
                            onTap: () {
                              setState(() {
                                // 这将触发整个GridView的重建，更新所有项的状态
                              });
                            },
                          );
                        } else {
                          return const Center(child: CircularProgressIndicator());
                        }
                      },
                    ),
                  ),

                  // 不可用内容
                  RefreshIndicator(
                    key: _refreshKey2,
                    onRefresh: () => Future.value(),
                    child: GridView.builder(
                      controller: _scrollController2,
                      padding: const EdgeInsets.all(16),
                      gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
                        maxCrossAxisExtent: 400,
                        childAspectRatio: 256 / 175,
                        crossAxisSpacing: 0,
                        mainAxisSpacing: 0,
                      ),
                      itemCount: _unusableItems.length + (_isLoading2 ? 1 : 0),
                      itemBuilder: (context, index) {
                        if (index < _unusableItems.length) {
                          return CouponCard(data: _unusableItems[index]);
                        } else {
                          return const Center(child: CircularProgressIndicator());
                        }
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

// 使用示例
void showCouponDialog(BuildContext context) {
  showGeneralDialog(
    context: context,
    barrierDismissible: true,
    barrierLabel: 'Tabbed Dialog',
    barrierColor: Colors.black.withOpacity(0.5),
    transitionDuration: const Duration(milliseconds: 300),
    pageBuilder: (context, animation, secondaryAnimation) {
      return const CouponSelectDialog();
    },
    transitionBuilder: (context, animation, secondaryAnimation, child) {
      return ScaleTransition(
        scale: CurvedAnimation(
          parent: animation,
          curve: Curves.easeOutCirc,
        ),
        child: child,
      );
    },
  );
}
